package com.rstrulak.managedBeans.controllers;

import java.io.IOException;
import java.io.Serializable;
import java.math.BigInteger;

import javax.servlet.ServletException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.rstrulak.dao.UserDao;
import com.rstrulak.model.User;
import com.rstrulak.utils.JSFUtils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Component("accountBean")
@Scope("request")
public class NewAccountBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6875636298565197744L;

	@Autowired
	UserDao userDao;

	private User user;

	private String firstName;

	private String lastName;

	private String mail;

	private String password;

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getMail() {
		return mail;
	}

	public void setMail(String mail) {
		this.mail = mail;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void createAccount() throws ServletException, IOException, NoSuchAlgorithmException {
		user = new User();
		user.setFirstName(firstName);
		user.setLastName(lastName);
		user.setEmail(mail);
		user.setPassword(encryptPassword(password));
		user.setLogin(generateLogin());

		userDao.save(user);
		JSFUtils.redirect("/public/login.xhtml");
	}

	public void cancel() throws ServletException, IOException {
		JSFUtils.redirect("/public/login.xhtml");
	}

	private String generateLogin() {
		return (firstName.charAt(0) + lastName).toLowerCase();
	}

	/**
	 * Generate password as md5 hash
	 * 
	 * @param password
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	private String encryptPassword(String password) throws NoSuchAlgorithmException {
		MessageDigest m = MessageDigest.getInstance("MD5");
		m.update(password.getBytes(), 0, password.length());
		String digest = new BigInteger(1, m.digest()).toString(16);
		return digest;
	}

}
